package com.xunshangwang.pinhaohuo.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.loopj.android.http.RequestParams;
import com.xunshangwang.pinhaohuo.R;
import com.xunshangwang.pinhaohuo.entity.Goods;
import com.xunshangwang.pinhaohuo.entity.GoodsGallery;
import com.xunshangwang.pinhaohuo.http.HttpTool;
import com.xunshangwang.pinhaohuo.http.JsonHttpHandler;
import com.xunshangwang.pinhaohuo.tools.SPHelper;
import com.xunshangwang.pinhaohuo.widgets.CircleIndicator;
import com.xunshangwang.pinhaohuo.widgets.LoadLayout;

import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import tool.library.ToastTool;
import tool.library.widget.AutoCycleViewPager;

/**
 * Created by xzp on 16/1/19.
 */
public class GoodsDetailActivity extends BaseActivity implements View.OnClickListener{
    private View mContentLayout;
    private String mGoodsId;
    private LoadLayout mLoad;
    private Goods mGoods;
    private View mGalleryLayout;
    private AutoCycleViewPager mGalleryPager;
    private CircleIndicator mGalleryIndicator;
    private TextView mGroupDescText,mGroupProcessingText,mGoodsNameText,
            mGoodDescText,mSellCountText,mPlayHintText,mGroupPriceText,mAlonePriceText,
            mGroupNumText;
    private WebView mBodyWeb;
    private TextView mCollectBtn,mShopBtn;
//    public static final Intent getIntent(Context context,String id){
//        Intent intent=new Intent(context,GoodsDetailActivity.class);
//        Uri uri=Uri.parse("pin://www.xunshangwang.com/goods/detail?id="+id);
//
//    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_detail);
        mGoodsId=getIntent().getData().getQueryParameter("id");
        findView();
        initView();
        requestDetail();
    }
    private void findView(){
        mContentLayout=this.findViewById(R.id.detail_content_layout);
        mLoad= (LoadLayout) this.findViewById(R.id.load_layout);
        mGalleryLayout=this.findViewById(R.id.goods_gallery_layout);
        mGalleryPager= (AutoCycleViewPager) this.findViewById(R.id.goods_gallery_pager);
        mGalleryIndicator= (CircleIndicator) this.findViewById(R.id.goods_gallery_indicator);
        mGoodsNameText= (TextView) this.findViewById(R.id.goods_name_text);
        mGroupProcessingText= (TextView) this.findViewById(R.id.goods_group_processing_text);
        mGroupDescText= (TextView) this.findViewById(R.id.goods_group_desc_text);
        mGoodDescText= (TextView) this.findViewById(R.id.goods_desc_text);
        mSellCountText= (TextView) this.findViewById(R.id.goods_sell_count_text);
        mBodyWeb= (WebView) this.findViewById(R.id.goods_body_web);
        mPlayHintText= (TextView) this.findViewById(R.id.group_play_hint_text);
        mGroupPriceText= (TextView) this.findViewById(R.id.goods_group_price_text);
        mAlonePriceText= (TextView) this.findViewById(R.id.goods_alone_price_text);
        mGroupNumText= (TextView) this.findViewById(R.id.goods_group_num_text);
        mCollectBtn= (TextView) this.findViewById(R.id.collect_btn);
        mShopBtn= (TextView) this.findViewById(R.id.shop_btn);
    }
    private void initView(){
        mContentLayout.setVisibility(View.GONE);
        mCollectBtn.setOnClickListener(this);
        mShopBtn.setOnClickListener(this);
        Drawable drawable=ContextCompat.getDrawable(this,R.drawable.shop_icon);
        drawable.clearColorFilter();
        mShopBtn.setCompoundDrawablesWithIntrinsicBounds(null,drawable,null,null);
        this.findViewById(R.id.service_guarantee_btn).setOnClickListener(this);
        this.findViewById(R.id.play_introduction_btn).setOnClickListener(this);
        this.findViewById(R.id.group_buy_btn).setOnClickListener(this);
        this.findViewById(R.id.personal_buy_btn).setOnClickListener(this);
        LinearLayout.LayoutParams params= (LinearLayout.LayoutParams) mGalleryLayout.getLayoutParams();
        int screenWidth= SPHelper.getIntValue(this, SPHelper.SP_CONFIG,SPHelper.SCREEN_WIDTH_PIXELS);
        params.height= (int) (screenWidth*0.53f);
        mGalleryIndicator.setViewPager(mGalleryPager);
        mBodyWeb.getSettings().setDefaultTextEncodingName("utf-8");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mBodyWeb.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
        } else {
            mBodyWeb.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        }
        mBodyWeb.getSettings().setJavaScriptEnabled(true);
        mBodyWeb.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mBodyWeb.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {

                }
                return true;
            }
        });
        mBodyWeb.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
    }
    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch (id){
            case R.id.collect_btn:
                requestCollect();
                break;
            case R.id.shop_btn:
                if(!TextUtils.equals(mGoods.getShop_id(),"0")) {
                    Intent shopIntent = new Intent(this, ShopDetailActivity.class);
                    shopIntent.putExtra("id", mGoods.getShop_id());
                    startActivity(shopIntent);
                }else {
                    ToastTool.showToast("暂无店铺");
                }
                break;
            case R.id.service_guarantee_btn:
                startActivity(new Intent(this,ServiceGuaranteeActivity.class));
                break;
            case R.id.play_introduction_btn:
                startActivity(new Intent(this,PlayIntroductionActivity.class));
                break;
            case R.id.group_buy_btn:
                startBuy(1);
                break;
            case R.id.personal_buy_btn:
                startBuy(0);
                break;
        }
    }

    private void startBuy(int groupBuy){
        if(!getMainApplication().isLogin()){
            ToastTool.showToast("请先登录再购买");
            return;
        }
        Intent intent=new Intent(this,CreateOrderActivity.class);
        Bundle bundle=new Bundle();
        bundle.putInt("groupBuy",groupBuy);
        bundle.putSerializable("goods",mGoods);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private void requestCollect(){
        if(mGoods==null)
            return;
        if(!getMainApplication().isLogin()) {
            ToastTool.showToast("请登录后再收藏");
            return;
        }
        StringBuilder builder=new StringBuilder("?g=Api&m=Favorites&a=toggleFavorites");
        builder.append("&fav_type=1");
        builder.append("&fav_id="+mGoodsId);
        builder.append("&token="+getMainApplication().getToken());
        HttpTool.get(this, builder.toString(), new JsonHttpHandler<String>() {
            @Override
            public void onStart() {
                super.onStart();
                mCollectBtn.setEnabled(false);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mCollectBtn.setEnabled(true);
            }

            @Override
            public String parseData(JSONObject object) throws Throwable {
                return object.getString("is_favorites");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, String response) {
                updateCollectState(TextUtils.equals(response,"1"));
                mGoods.setIs_favorites(response);
            }
        });
    }
    private void updateCollectState(boolean isCollect){
        if(isCollect){
            mCollectBtn.setText("已收藏");
            mCollectBtn.setTextColor(ContextCompat.getColor(this, R.color.red));
            mCollectBtn.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(this, R.drawable.goods_collect_icon), null, null);
        }
        else {
            mCollectBtn.setText("未收藏");
            mCollectBtn.setTextColor(ContextCompat.getColor(this, R.color.gray));
            mCollectBtn.setCompoundDrawablesWithIntrinsicBounds(null,ContextCompat.getDrawable(this,R.drawable.goods_not_collect_icon),null,null);
        }
    }
    private void requestDetail(){
        StringBuilder builder=new StringBuilder("?g=Api&m=Goods&a=detail");
        builder.append("&goods_id="+mGoodsId);
        if(getMainApplication().isLogin())
            builder.append("&token="+getMainApplication().getToken());
        HttpTool.get(this, builder.toString(), new JsonHttpHandler<Goods>() {
            @Override
            public void onStart() {
                super.onStart();
                mLoad.startLoad();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mLoad.finishLoad();
            }

            @Override
            public Goods parseData(JSONObject object) throws Throwable {
                Goods goods = JSON.parseObject(object.getString("goods"), Goods.class);
                if (goods != null) {
                    List<GoodsGallery> galleryList = JSON.parseArray(object.getString("gallery"), GoodsGallery.class);
                    goods.setGalleryList(galleryList);
                }
                return goods;
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, Goods errorResponse) {
                super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
                if(mGoods==null)
                    finish();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Goods response) {
                mGoods = response;
                if (response != null) {
                    mContentLayout.setVisibility(View.VISIBLE);
                    DecimalFormat format = new DecimalFormat("0.00");
                    GalleryAdapter adapter = new GalleryAdapter(response.getGalleryList());
                    mGalleryPager.setAdapter(adapter);
                    mGalleryIndicator.notifyDataSetChanged();
                    mGoodsNameText.setText(response.getGoods_name());
                    SpannableStringBuilder desBuilder = new SpannableStringBuilder();
                    desBuilder.append(response.getGroup_number() + "人拼团价:");
                    SpannableString unitStr = SpannableString.valueOf("￥");
                    unitStr.setSpan(new AbsoluteSizeSpan(14, true), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    desBuilder.append(unitStr);
                    SpannableString groupPriceStr = SpannableString.valueOf(format.format(response.getGroup_price()));
                    groupPriceStr.setSpan(new AbsoluteSizeSpan(20, true), 0, groupPriceStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    desBuilder.append(groupPriceStr);
                    desBuilder.append("/件");
                    mGroupDescText.setText(desBuilder);
                    mGroupProcessingText.setText(mGoods.getGroup_goods_count() + "个团正在进行中");
                    mGoodDescText.setText(mGoods.getGoods_desc());
                    mSellCountText.setText("已售: " + response.getSell_count() + " 件");
                    mBodyWeb.loadData(getHtmlData(response.getGoods_body()), "text/html; charset=utf-8", "utf-8");
                    mPlayHintText.setText("支付开团并邀请" + (response.getGroup_number() - 1) + "人开团,人数不足自动退款，详见下方拼团玩法");
                    mGroupPriceText.setText("￥"+format.format(response.getGroup_price()) + "/件");
                    mGroupNumText.setText(mGoods.getGroup_number() + "人开团");
                    mAlonePriceText.setText("￥"+format.format(response.getAlone_price()) + "/件");
                    if(getMainApplication().isLogin()){
                        updateCollectState(TextUtils.equals(response.getIs_favorites(),"1"));
                    }
                }
            }
        });
    }
    private String getHtmlData(String bodyHTML) {
        String head = "<head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
                "<style>img{max-width: 100%; width:auto; height:auto;}</style>" +
                "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }
    private class GalleryAdapter extends AutoCycleViewPager.CyclePagerAdapter<GoodsGallery>{
        public GalleryAdapter(List<GoodsGallery> list) {
            super(list);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView=new ImageView(GoodsDetailActivity.this);
            ViewGroup.LayoutParams params=new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            container.addView(imageView,params);
            GoodsGallery gallery=getList().get(position%getList().size());
            Glide.with(GoodsDetailActivity.this).load(gallery.getImage_url()).centerCrop().into(imageView);
            return imageView;
            //return super.instantiateItem(container, position);
        }
    }
}
